#pragma once
#include<iostream>
#include<string>
#include<vector>
#include<functional>
#include"InetAddr.hpp"
#include<pthread.h>
#include"ThreadPool.hpp"
#include"Thread.hpp"
#include"LockGuard.hpp"
using task_t = std::function<void()>; 
class Route
{
public:
    Route()
    {
        pthread_mutex_init(&_mutex,nullptr);
    }
    bool CheckOnlineUser(InetAddr who)
    {
        for(auto e : _online_user)
        {
            if(e == who)
            {
                return true;
            }
        }
        return false;
    }
    void Offline(InetAddr& who)
    {
        for(auto e : _online_user)
        {
            if(e == who)
            {
                _online_user.pop_back();
                break;
            }
        }
    }
    void ForwardHelper(int sockfd,const std::string &message,InetAddr & who)
    {
        LockGuard lock(&_mutex);
        for(auto& e : _online_user)
        {
            const std::string sendmessage = "["+who.AddStr()+"]"+message;
            ::sendto(sockfd,&sendmessage,sendmessage.size(),0,(struct sockaddr*)&who.Addr(),who.Len());
        }
    }
    void Forward(int sockfd,const std::string &message,InetAddr & who)
    {
        //1.检查who是否在在线用户列表里
        if(!CheckOnlineUser(who))
        {
            _online_user.push_back(who);
        }
        //2.删除逻辑
        if(message == "Quit" || message == "Q")
            Offline(who);
        //转发，压到线程池的任务队列里，线程池只要任务队列不为空并且是处于运行状态就会处理转发任务
        task_t func = std::bind(&Route::ForwardHelper,this,sockfd,message,who);
        ThreadPool<task_t>::GetInstance()->Equeue(func);
    }
    ~Route()
    {
        pthread_mutex_destroy(&_mutex); 
    }
private:
    std::vector<InetAddr> _online_user;
    pthread_mutex_t _mutex;
};